<template>
  <div>
    <div class="part part-1" @drop="drop">
      <h2>vue实现拖拽，使用drag和drop</h2>
      <div class="info">
        拖拽对象：{{dragObj}} 初始位置：{{x}}:{{y}} 鼠标位置：{{mouseX}} : {{mouseY}}, 定位：{{top}}:{{left}}
      </div>
      <div ref="box" class="box" draggable="true" @dragstart="dragStart" @drag="drag" @dragend="dragEnd">这是一个可拖拽的box</div>
    </div>
  </div>
</template>

<script>
  export default {
    name: "drag",
    data() {
      return {
        dragging: false,
        dragObj: null,
        top: 0,
        left: 0,
        mouseX: 0,
        mouseY: 0,
        x: 0,
        y: 0
      }
    },
    methods: {
      drop(evt) {
        console.log(evt);
      },
      dragStart(e, dom) {
        console.log('start', e, dom);
        this.dragging = true;
        this.top = Number(e.currentTarget.style.top.replace('px', ''));
        this.left = Number(e.currentTarget.style.left.replace('px', ''));
        this.x = this.mouseX = e.clientX;
        this.y = this.mouseY = e.clientY;

        setTimeout(_ => {
          e.target.style.display = 'none'
        });

      },
      drag(e) {
        // e是鼠标对象，这里需要弄清楚screenX, clientX,
        // screenX: 鼠标距离屏幕的x轴距离，以左上角为原点，向下或者向左都是正数。
        // clientX: 鼠标距离本地内容的dom的x轴距离，以什么为原点呢？
        // pageX: 鼠标距离页面的x轴距离，以整个页面为原点。
        // offsetX: 鼠标距离初始位置的x轴距离，以初始点击点为原点
        // layerX:
        // x: 和pageX差不多
        // console.log(e);
        this.mouseX = e.clientX;
        this.mouseY = e.clientY;
        // this.y = e.offsetY - this.y;
      },
      dragEnd(e) {
        console.log('end', e)
        let box = this.$refs.box;
        this.top = this.top + e.offsetX - this.x;
        this.left = this.left + e.offsetY - this.y
        box.style.top = `${this.top}px`;
        box.style.left = `${this.left}px`;
        setTimeout(_ => {
          box.style.display = 'block'
        })

      }
    }
  }
</script>

<style scoped>
.box{
  width: 100px;
  height: 100px;
  background: deepskyblue;
  position: relative;
  top: 0;
  left: 0;
}
</style>
